package com.example.qihuibao.module.service

import android.app.IntentService
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.example.qihuibao.XApplication
import com.example.qihuibao.utils.CommonUtil
import com.example.qihuibao.utils.NetworkUtil

/**
 * 定时检查网络是否正常
 */
class NetworkStatusService : IntentService("") {
    private var callback:CallBack? = null
    private var period = 10000L

    override fun onBind(intent: Intent?): IBinder {
        return MyBinder()
    }

    override fun onHandleIntent(intent: Intent?) {
        while (true) {
            if (!NetworkUtil.isNetworkAvailable(XApplication.application)) {//网络未连接
                this.callback?.getNetworkStatus(false)
                Thread.sleep(period/2)
                continue
            }
            val status = CommonUtil.isConnectNetwork2()
            this.callback?.getNetworkStatus(status)
            Thread.sleep(if(status) period*2 else period/2)
        }
    }

    fun setCallback(callBack: CallBack) {
        this.callback = callBack
    }

    inner class MyBinder : Binder() {
        fun getService(): NetworkStatusService {
            return this@NetworkStatusService
        }
    }

    interface CallBack {
        fun getNetworkStatus(ok:Boolean)
    }
}